﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace KLS.PPDS.Utilities
{
    /// <summary>
    /// Represend Cryptography
    /// </summary>
    public static class CryptographyHelper
    {
        /// <summary>
        /// calculate hash for a given input
        /// </summary>
        /// <param name="input"></param>
        /// <param name="algorithm"></param>
        /// <returns> hashed string for given input</returns>
        public static string CalculateHash(string input, HashAlgorithm algorithm)
        {
            byte[] hash;
            var inputBytes = Encoding.ASCII.GetBytes(input);

            switch (algorithm)
            {
                case HashAlgorithm.MD5:
                    var md5 = MD5.Create();
                    hash = md5.ComputeHash(inputBytes);

                    break;
                case HashAlgorithm.SHA256:
                    var sha256 = SHA256.Create();
                    hash = sha256.ComputeHash(inputBytes);

                    break;
                case HashAlgorithm.SHA512:
                    var sha512 = SHA512.Create();
                    hash = sha512.ComputeHash(inputBytes);

                    break;
                default:
                    throw new ArgumentOutOfRangeException("algorithm");
            }


            var sb = new StringBuilder();
            for (var i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }

            return sb.ToString();

        }

        /// <summary>
        /// Provides attibute for calculationg hash
        /// </summary>
        public enum HashAlgorithm
        {
            ///<summary>
            /// The 128-bit (16-byte) MD5 hashes (also termed message digests) are typically represented as a sequence of 32 hexadecimal digits
            ///</summary>
            MD5,
            ///<summary>
            /// SHA-256 uses 32-byte (256 bits) words 
            ///</summary>
            SHA256,
            ///<summary>
            /// SHA-512 uses 64-byte (512 bits) words
            ///</summary>
            SHA512
        }

    }
}
